package com.atguigu.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class MyLb implements LoadBalaner{

    //int的原子性,线程安全
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    public final int getAtoIncrement(){

        int current;
        int next;
        do {
            current  = this.atomicInteger.get();
            next = current >= Integer.MAX_VALUE ? 0 : current + 1;
        }while (!this.atomicInteger.compareAndSet(current, next));
        //ato和curr一样是返回true，然后更新next值到ato

        System.out.println("第几次访问："+this.atomicInteger.get());

        return this.atomicInteger.get();
    }

    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
        int i = getAtoIncrement() % serviceInstances.size();
        ServiceInstance serviceInstance = serviceInstances.get(i);
        return serviceInstance;
    }
}
